/**
 * 入参
 *
 */
import React, { PureComponent } from 'react';
import { PrimaryC, SelectC, ModalC, PrimaryGhostC } from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Radio, Input, message } from 'antd';
import style from '../index.less';
import { connect } from 'dva';

class ProgrammeSelectC extends PureComponent {
  static defaultProps = {};
  state = {
    dataList: [], //筛选方案下拉列表
    isDisabled: false, //保存按钮是否显示
    selectOption: undefined, //当前选中的方案
    saveType: 1, //保存类型 默认新建1 编辑保存2
    visible: false, //模态框显示
    newName: undefined, //新建名称name
    editName: undefined, //编辑名称
  };
  componentDidMount() {
    this.props.onRef(this);
    if (this.props.currentUser.userId && this.props.loadingOff) {
      this.getScreenSchemeList(this.props.currentUser.userId);
    }
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    //刷新的时候 didmount里请求 会导致getuser 也有iv-user
    // console.log(this.props.loadingOff,nextProps.loadingOff)
    if ((this.props.currentUser.userId != nextProps.currentUser.userId && !this.props.currentUser.userId) || this.props.loadingOff != nextProps.loadingOff) {
      this.getScreenSchemeList(nextProps.currentUser.userId);
    }
  }

  //获取筛选方案列表
  getScreenSchemeList = (userId, id) => {
    this.props.dispatch({
      type: 'AssetPreparationM/getScreenSchemeList',
      payload: {},
      callback: (data) => {
        if (data) {
          //请求成功
          const indicatorList = this.props.AssetPreparationM.indicatorList || [];
          data.map((item) => {
            //指标相关基础数据---翻译筛选方案type名称
            let arr = indicatorList.length
              ? indicatorList.filter((obj) => {
                  return obj.value === item.type;
                })
              : [];
            if (arr.length) {
              item.title = item.title + '-' + arr[0].title;
            }
          });
          this.setState({
            dataList: data || [],
          });
          if (id) {
            //新增完定位到当前id
            const arr = data.filter((item) => {
              return item.value === id;
            });
            this.setState({
              isDisabled: arr[0].isSystem == 1 ? true : false,
              selectOption: arr[0],
            });
          }
        } else {
          //请求失败清空
          this.setState({
            dataList: [],
          });
        }
      },
    });
  };
  //获取方案详情
  getDetail = (id) => {
    this.props.dispatch({
      type: 'AssetPreparationM/getScreenSchemeDetail',
      payload: { id },
      callback: (data) => {
        this.props.getDetail(data);
      },
    });
  };
  //切换方案事件 判断是否可编辑
  handleChangeId = (e) => {
    if (e) {
      const arr = this.state.dataList.filter((item) => {
        return item.value === e;
      });
      if (!arr.length) return;
      this.setState({
        isDisabled: arr[0].isSystem == 1 ? true : false,
        selectOption: arr[0],
      });
      this.getDetail(arr[0].value); //查询方案详情
    } else {
      this.setState({
        isDisabled: false,
        selectOption: undefined,
      });
    }
  };

  //清空页面到初始化状态
  reset = () => {
    this.setState({
      isDisabled: false, //保存按钮是否显示
      selectOption: undefined, //当前选中的方案
      saveType: 1, //保存类型 默认新建1 编辑保存2
      visible: false, //模态框显示
      newName: undefined, //新建名称
      editName: undefined, //编辑名称
    });
    this.fanganRef.setSelect(undefined);
    this.props.onClear(); //清空页面通知父组件
  };

  //新增或者编辑方案名
  handleOk = () => {
    const { saveType, editName, newName, selectOption } = this.state;
    const { dispatch, type, settingInfo } = this.props;
    const name = saveType == 1 ? newName : editName;
    if (name && name.replace(/\s/g, '').length) {
      //校验名字程度
      const indexList = settingInfo();
      if (indexList) {
        //校验条件设置里的数据，有数据返回就上传
        dispatch({
          //保存接口
          type: 'AssetPreparationM/addUpdate',
          payload: {
            id: saveType == 1 ? undefined : selectOption.value, //保存时的方案id
            name, //方案名称
            type,
            index: indexList,
          },
          callback: (data) => {
            if (data) {
              //请求成功
              message.success('方案上传成功!');
              // this.reset();
              this.fanganRef.setSelect(data);
              this.handleCancel();
              this.getScreenSchemeList(this.props.currentUser.userId, data); //重新查询方案列表
              this.getDetail(data); //查询详情
            }
          },
        });
      }
    } else {
      const msg = saveType == 1 ? '新建' : '保存为';
      message.error(`${msg}的方案名称必填`);
      return;
    }
  };

  //点击取消按钮
  handleCancel = () => {
    this.setState({
      visible: false,
      saveType: 1, //保存类型 默认新建1 编辑保存2
      newName: undefined, //新建名称
      editName: undefined,
    });
  };

  inputChange = (e, name) => {
    this.setState({
      [name]: e ? e.target.value.replace(/\s/g, '') : undefined,
    });
  };

  //展示模态框
  showModal = () => {
    const { visible, saveType, newName, editName } = this.state;
    const { loading } = this.props;
    const modalProps = {
      visible: visible,

      onOk: () => {
        this.handleOk();
      },
      onCancel: () => {
        this.handleCancel();
      },
      confirmLoading: loading.effects['AssetPreparationM/addUpdate'] === true,
      okText: '确定',
      title: '保存方案',
      className: 'modalPlan',
      height: 110, //内容区域的高度
      width: 310,
    };
    const radioStyle = {
      display: 'block',
      height: '30px',
      lineHeight: '30px',
      marginBottom: '15px',
      marginRight: 0,
    };
    return (
      <ModalC {...modalProps}>
        <Radio.Group onChange={(e) => this.setState({ saveType: e.target.value })} value={saveType}>
          <Radio style={radioStyle} value={1} key={1}>
            <i className='labeli'>新建:</i>
            <Input style={{ width: 200, marginLeft: 5 }} value={newName} onChange={(e) => this.inputChange(e, 'newName')} placeholder='请输入方案名称' />
          </Radio>
          <Radio style={radioStyle} value={2} key={2} disabled={!this.state.selectOption}>
            <i className='labeli'>保存为:</i>
            <Input style={{ width: 200, marginLeft: 5 }} value={editName} onChange={(e) => this.inputChange(e, 'editName')} placeholder='请输入方案名称' />
          </Radio>
        </Radio.Group>
      </ModalC>
    );
  };
  render() {
    const { isDisabled, dataList, visible, selectOption } = this.state;
    return (
      <div className={style.planList}>
        <div>
          <SelectC
            form={this.props.form} // form对象
            title='筛选方案' // 显示名称
            dataIndex='id' // Form识别的Item ID
            dataSource={dataList}
            showSearch={false}
            onChange={this.handleChangeId}
            onRef={(ref) => (this.fanganRef = ref)}
          />
        </div>
        <div>
          <PrimaryC
            title='保存'
            disabled={isDisabled || !this.props.settingInfo}
            onClick={() => {
              if (selectOption) this.setState({ editName: selectOption.title ? selectOption.title.split('-')[0] : selectOption.title, saveType: 2 });
              this.setState({ visible: true });
            }}
          />
          <PrimaryGhostC title='清空' onClick={this.reset} />
          <div>
            <PrimaryC title='筛选方案' onClick={() => this.props.changePage(2)} />
          </div>
        </div>
        {visible ? this.showModal() : null}
      </div>
    );
  }
}
export default connect(({ AssetPreparationM, userM: user, loading }) => ({
  AssetPreparationM,
  currentUser: user.currentUser,
  loading,
}))(Form.create()(ProgrammeSelectC));
